# coding: utf-8
from datetime import datetime, timedelta
from leancloud import Engine, Object, Query
from dbModels import AgmSellCount

from app import app


engine = Engine(app)


@engine.define
def hello(**params):
    print 'Hello!'
    if 'name' in params:
        return 'Hello, {}!'.format(params['name'])
    else:
        return 'Hello, LeanCloud!I\'m Fun'

@engine.define
def saveWechatKfLog():
    #--------saveWechatLog-----#
    from tools.wechatAPI import getkfrecord
    ret = getkfrecord(1)
    recordlist = ret.get('recordlist')
    WechatKfLog = Object.extend('WechatKfLog')
    for t in recordlist:
        wechatkflog = WechatKfLog()
        for k in t:
            wechatkflog.set(k, t[k])
        wechatkflog.save()
    print 'SaveWechatKfLog Done! %s logs saved' % len(recordlist)
    #---------delRepeatWechatUser-----#
    repeatset = set()
    repeatset1 = set()
    query = Query(Object.extend('WechatUser'))
    query.greater_than('createdAt', datetime.now() - timedelta(days=2))
    query.descending('createdAt').limit(1000)
    users = query.find()
    for u in users:
        openid = u.get('openid')
        if openid not in repeatset:
            repeatset.add(openid)
        else:
            repeatset1.add(openid)
            u.destroy()
            print 'Repeat Openid:%s Deleted!' % (openid)
    if not repeatset1:
        print 'No Repeat!'
    print 'DelRepeatWechatUser Done! %s users deleted' % len(repeatset1)
    #-----saveSellCountToYesterdayLastWeekLastMonth----#
    now = datetime.now()
    isMonday = True if now.weekday() == 0 else False
    isFirstday = True if now.day == 1 else False
    counts = Query(AgmSellCount).find()
    for c in counts:
        today =  c.get('today')
        c.set('yesterday', today)
        c.increment('today', -today)
        if isMonday:
            week = c.get('week')
            c.set('lastweek', week)
            c.increment('week', -week)
        if isFirstday:
            month = c.get('month')
            c.set('lastmonth', month)
            c.increment('month', -month)
        c.save()
    print 'RefreshAgmSellCount Done! %s counts refreshed!' % (len(counts))

@engine.define
def saveUrltoFile():
    from tools.saveFile import saveFile
    saveFile('Agm_Product_beta', ['img', 'img_ch', 'img_pz', 'img_sm', 'img_td'], ['imgfile', 'imgfile_ch', 'imgfile_pz', 'imgfile_sm', 'imgfile_td'])
        